import React, { Component } from 'react';
import "../../src/view/Login.scss";
import pic from '../../src/components/Login/imgs/pic.png';
import { user_login } from '../../src/utils/api.js';
import { good_favlist } from '../utils/api'
import store from '../store/index.js'

class Login extends Component {
    //挂载期
    constructor(props) {
        super(props);
        this.state = {
            pic: pic,
            phone: '',
            pass: '',
        }
    }
    //自定义函数
    login() {
        var phoneReg = /^1[3,5,7]\d{9}$/;
        var passReg = /^\w{6,}$/;
        if (!phoneReg.test(this.state.phone)) {
            alert("请输入合法的手机号");
            if (!passReg.test(this.state.pass)) {
                alert('请输入至少六位密码');
                if (this.state.checked) {
                    alert("勾选才能登录");
                } else {
                    alert("勾选才能登录")
                }
            }
        } else {
            user_login({ phone: this.state.phone, pass: this.state.pass }).then((res) => {
                alert(res.data.msg);
                localStorage.setItem("token", res.data.token);
                localStorage.setItem("userInfo", JSON.stringify(res.data.userinfo));
                var userid = JSON.parse(localStorage.getItem("userInfo")).id
                this.props.history.push("/index")
                good_favlist({ userid }).then((res) => {
                    store.dispatch({ type: "STORE_FAVOR_LIST", payload: res.data.list })
                    localStorage.setItem("favorlist", JSON.stringify(res.data.list))
                })
            })
        }
    }
    handleChange(e) {
        this.setState({
            [e.target.name]: (e.target.type === 'checkbox' || e.target.type === 'radio') ? e.target.checked : e.target.value,
        })
    }

    render() {
        return (
            <div className='login_page'>
                <div className='logoBox'>
                    <img src={pic} alt="" />
                </div>
                <div className='userInfo'>
                    <input type="text" name="phone" placeholder='请输入用户名' value={this.state.phone} onChange={(e) => {
                        this.handleChange(e)
                    }} />
                    <input type="password" name="pass" placeholder='请输入密码' value={this.state.pass} onChange={(e) => {
                        this.handleChange(e)
                    }} />
                </div>
                <div className='login'>
                    <input type="button" value="登录" onClick={() => {
                        this.login()
                    }} />
                </div>
                <div className="register">
                    <a onClick={() => {
                        this.props.history.push("/register")
                    }}>注册</a>

                </div>
            </div>
        );
    }
}

export default Login;
